package com.soledroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.droidfu.widgets.WebImageView;
import com.soledroid.Model.Dish;
import com.soledroid.Model.Stall;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class StallActivity extends Activity {
	private LayoutInflater mInflater;
	protected String name;
	protected String imgRes;
	protected int id;
	private TextView mStallNameView;
	private ImageView mStallImageView;
	private Button checkinBtn;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stall);
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

		id = getIntent().getExtras().getInt("id");
		name = getIntent().getExtras().getString("name");
		imgRes = getIntent().getExtras().getString("img_res");
		
		checkinBtn = (Button) findViewById(R.id.checkin_btn);
		checkinBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	Intent i = new Intent(getApplicationContext(),
						CheckinActivity.class);

				i.putExtra("name", name);
				i.putExtra("id", id);

				StallActivity.this.startActivity(i);
            }
		});

		mStallNameView = (TextView) findViewById(R.id.stall_name);
		mStallNameView.setText(name);

		mStallImageView = (ImageView) findViewById(R.id.stall_img);
		try {
			mStallImageView.setImageDrawable(Drawable.createFromStream(Utils.fetchImage(imgRes), "src"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		final ArrayList<Dish> dishes = this.fetchDishes();

		CustomAdapter adapter = new CustomAdapter(this, R.layout.stall_list_entry, R.id.stall_food_name, dishes);
		ListView lv = (ListView) findViewById((R.id.stallListView));
		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(getApplicationContext(),
						DishActivity.class);

				Dish dish = dishes.get(position);
				i.putExtra("name", dish.getName());
				i.putExtra("id", dish.getId());

				StallActivity.this.startActivity(i);
			}
		});
	}

	public ArrayList<Dish> fetchDishes() {
		ArrayList<Dish> listItems = new ArrayList<Dish>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/stall/" + id + "/dishes");
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);

				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);

					Dish dish = new Dish(jo.getInt("id"), jo.getString("name"),
							jo.getString("image"), jo.getString("description"),
							jo.getString("price"), jo.getInt("stall_id"),
							jo.getInt("on_promotion") == 1,
							jo.getDouble("rating"));
					listItems.add(dish);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return listItems;
	}

	private class CustomAdapter extends ArrayAdapter<Dish> {
		public CustomAdapter(Context context, int resource,
				int textViewResourceId, List<Dish> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			TextView foodNameView = null;
			TextView foodPriceView = null;
			WebImageView foodImageView = null;
			RatingBar foodRatingBar = null;
			Dish rowData = getItem(position);

			if (convertView == null) {
				convertView = mInflater
						.inflate(R.layout.stall_list_entry, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			foodNameView = holder.getTitleView();
			foodNameView.setText(rowData.getName());
			
			foodPriceView = holder.getPriceView();
			if(rowData.getDescription().equals("null")){
				foodPriceView.setText("$" + rowData.getPrice());
			} else{
				foodPriceView.setText("$" + rowData.getPrice() + " - " + rowData.getDescription());
			}
			

			foodImageView = holder.getImageView();
			if (rowData.getImage() == null) {
				//foodImageView.setImageUrl(R.drawable.not_available);
			} else {
				try {
					foodImageView.setImageUrl(rowData.getImage());
					foodImageView.loadImage();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			foodRatingBar = holder.getRatingBar();
			foodRatingBar.setRating((float)rowData.getRating());

			return convertView;
		}

		public InputStream fetchImage(String address)
				throws MalformedURLException, IOException {
			URL url = new URL(address);
			Object content = url.getContent();
			return (InputStream) content;
		}
	}

	private class ViewHolder {
		private View mRow;
		private TextView mNameView = null;
		private TextView mPriceView = null;
		private WebImageView mImageView = null;
		private RatingBar mRatingBar = null;

		public ViewHolder(View row) {
			mRow = row;
		}

		public TextView getTitleView() {
			if (mNameView == null) {
				mNameView = (TextView) mRow.findViewById(R.id.stall_food_name);
			}
			return mNameView;
		}
		
		public TextView getPriceView() {
			if (mPriceView == null) {
				mPriceView = (TextView) mRow.findViewById(R.id.stall_food_price);
			}
			return mPriceView;
		}

		public WebImageView getImageView() {
			if (mImageView == null) {
				mImageView = (WebImageView) mRow.findViewById(R.id.stall_food_img);
			}
			return mImageView;
		}
		
		public RatingBar getRatingBar() {
			if (mRatingBar == null) {
				mRatingBar = (RatingBar) mRow.findViewById(R.id.stall_food_rating);
			}
			return mRatingBar;
		}
	}

	public void addComment(String comment) {

	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			boolean result = super.onCreateOptionsMenu(menu);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu, menu);
			return result;
		}
	    
	    @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent i;
			switch(item.getItemId()) {
			case R.id.menu_search:
				onSearchRequested();
				return true;
			case R.id.menu_preferences:
				showPreferences();
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
	    
	    private void showPreferences() {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
		}

}
